package com.risetechnology.krystalkitchen1;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.util.Patterns;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

import com.risetechnology.adapter.RecipeUpdateListAdapter;
import com.risetechnology.data.RecipeUpdate;
import com.risetechnology.master.NavigationActivity;
import com.risetechnology.utils.IabHelper;
import com.risetechnology.utils.IabResult;
import com.risetechnology.utils.Inventory;
import com.risetechnology.utils.Purchase;
import com.risetechnology.utils.Utils;
import com.risetechnology.utils.threads.PurchaseRecipeTask;

public class ActivityUpdate extends NavigationActivity {

	static final String TAG = "ActivityUpdate";

	private ListView listviewRecipes;
	private List<RecipeUpdate> recipesList;
	private RecipeUpdateListAdapter listAdapter;
	public static final String BASE_64_ENCODED_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxS5cq08kk3bLNmEjRsvXOJ7wjzPnAM5bvK/7kBnSeHDlSwF0TYM5Z64M8+swB9wm9vsTb46pr/IZHIEOJynihC4oyhevWiNqR0yiEcdln8Phv4mErDnVszziWq6wgfaFgd4Gzq7aEVEqHjXFa3JSgpUKiXqs+iTAQ3StdyMrB8zwzSYfSrA/5KCIBtg334QyClw/oNUT9WICNws/unI0RITct6uetkJfBkcKcHLYnr7de+aCQ5nwbxPfg0ZHpyqljI8eWruLrYc6B+NyDlsJeDjORLtj/aOnVJRFSfe7HoIin77ERqy1+tdWnA9+7nwe9zs6zzqYQMn4h98lUOeWjwIDAQAB";
	private final int REQ_PURCHASE = 1001;
	private String PURCHASE_SKU = "com.risetechnology.krystalkitchen1.extrarecipe1";
	private IabHelper mHelper;
	private RecipeUpdate purchasingPackage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_update);

		// Set contents
		setContents();

		mHelper = new IabHelper(this, BASE_64_ENCODED_PUBLIC_KEY);

		// enable debug logging (for a production application, you should set
		// this to false).
		mHelper.enableDebugLogging(true);
		try {
			mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
				public void onIabSetupFinished(IabResult result) {
					Log.d(TAG, "Setup finished.");

					if (!result.isSuccess()) {
						// Oh noes, there was a problem.
						return;
					}

					// Have we been disposed of in the meantime? If so, quit.
					if (mHelper == null)
						return;

					// IAB is fully set up. Now, let's get an inventory of stuff we
					// own.
					Log.d(TAG, "Setup successful. Querying inventory.");
					mHelper.queryInventoryAsync(mGotInventoryListener);
				}
			});
		} catch (Exception e) {}
		

	}

	@SuppressLint("SimpleDateFormat")
	private void setContents() {
		listviewRecipes = (ListView) findViewById(R.id.lv_recipes);
		recipesList = new ArrayList<RecipeUpdate>();

		getRecipeUpdate();
	}

	private void getRecipeUpdate() {
		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(this).getAccounts();
		if (accounts.length != 0)
			for (Account acc : accounts) {
				if (emailPattern.matcher(acc.name).matches()) {
					new TaskGetRecipeUpdate().execute(acc.name);
					break;
				}
			}
		else {
			 Toast.makeText(this, "Not have gmail account",
			 Toast.LENGTH_SHORT).show();
		}
	}

	public void lauchPurchase(RecipeUpdate item) {
		purchasingPackage = item;
		mHelper.launchPurchaseFlow(getParent(), PURCHASE_SKU, REQ_PURCHASE,
				mPurchaseFinishedListener);
	}

	IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
		public void onQueryInventoryFinished(IabResult result,
				Inventory inventory) {
			Log.d(TAG, "Query inventory finished.");

			// Have we been disposed of in the meantime? If so, quit.
			if (mHelper == null)
				return;
			// Is it a failure?
			if (result.isFailure()) {
				// complain("Failed to query inventory: " + result);
				return;
			}
			Purchase recipePurchase = inventory.getPurchase(PURCHASE_SKU);
			if (recipePurchase != null
					&& verifyDeveloperPayload(recipePurchase)) {
				Log.d(TAG, "We have gas. Consuming it.");
				mHelper.consumeAsync(inventory.getPurchase(PURCHASE_SKU),
						mConsumeFinishedListener);
				return;
			}

			Log.d(TAG, "Query inventory was successful.");
			Log.d(TAG, "Initial inventory query finished; enabling main UI.");
		}
	};
	IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
		public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
			Log.d(TAG, "Purchase finished: " + result + ", purchase: "
					+ purchase);

			// if we were disposed of in the meantime, quit.
			if (mHelper == null) {
				purchasingPackage = null;
				return;
			}

			if (result.isFailure()) {
				purchasingPackage = null;
				return;
			}
			if (!verifyDeveloperPayload(purchase)) {
				purchasingPackage = null;
				return;
			}

			Log.d(TAG, "Purchase successful.");

			if (purchase.getSku().equals(PURCHASE_SKU)) {
				mHelper.consumeAsync(purchase, mConsumeFinishedListener);
				Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
				Account[] accounts = AccountManager.get(
						ActivityUpdate.this.getParent()).getAccounts();
				if (accounts.length != 0)
					for (Account acc : accounts) {
						if (emailPattern.matcher(acc.name).matches()) {
							new PurchaseRecipeTask(getParent(), acc.name,
									purchasingPackage).execute();
							break;
						}
					}
				else {
					// Toast.makeText(this, "Not have gmail account",
					// Toast.LENGTH_SHORT).show();
				}
				purchasingPackage.setPurchased(true);
				purchasingPackage = null;

			}

		}
	};

	// Called when consumption is complete
	IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
		public void onConsumeFinished(Purchase purchase, IabResult result) {
			Log.d(TAG, "Consumption finished. Purchase: " + purchase
					+ ", result: " + result);

			// if we were disposed of in the meantime, quit.
			if (mHelper == null)
				return;

			if (result.isSuccess()) {
			} else {
			}
			Log.d(TAG, "End consumption flow.");
		}
	};

	// We're being destroyed. It's important to dispose of the helper here!
	@Override
	public void onDestroy() {
		super.onDestroy();

		// very important:
		Log.d(TAG, "Destroying helper.");
		if (mHelper != null) {
			mHelper.dispose();
			mHelper = null;
		}
	}

	boolean verifyDeveloperPayload(Purchase p) {
		String payload = p.getDeveloperPayload();

		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + ","
				+ data);
		if (mHelper == null)
			return;

		if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
			super.onActivityResult(requestCode, resultCode, data);
		} else {
			Log.d(TAG, "onActivityResult handled by IABUtil.");
		}
	}

	private class TaskGetRecipeUpdate extends
			AsyncTask<String, Void, List<RecipeUpdate>> {
		private ProgressDialog mDialog;

		@Override
		protected List<RecipeUpdate> doInBackground(String... params) {
			List<RecipeUpdate> recipeUpdates = new ArrayList<RecipeUpdate>();
			if (Utils.isNetworkConnected(ActivityUpdate.this.getParent())) {
				try {
					HttpParams httpParameters = new BasicHttpParams();
					// Set the timeout in milliseconds until a connection is
					// established.
					int timeoutConnection = 30000;
					HttpConnectionParams.setConnectionTimeout(httpParameters,
							timeoutConnection);
					// Set the default socket timeout (SO_TIMEOUT)
					// in milliseconds which is the timeout for waiting for
					// data.
					int timeoutSocket = 30000;
					HttpConnectionParams.setSoTimeout(httpParameters,
							timeoutSocket);
					HttpClient httpclient = new DefaultHttpClient(
							httpParameters);
					HttpPost httppost = new HttpPost(
							"http://cloud2.rise.ws/krystalkitchen/webservices/getAllPackages.php");
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
							2);
					nameValuePairs.add(new BasicNameValuePair("email",
							params[0]));
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					HttpResponse result = httpclient.execute(httppost);

					HttpEntity resultEntity = result.getEntity();

					InputStream instream = resultEntity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(instream));
					String line;
					StringBuffer res;
					res = new StringBuffer();
					while ((line = reader.readLine()) != null) {
						res.append(line);
					}
					JSONArray jsonArray = new JSONArray(res.toString());
					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject obj = jsonArray.getJSONObject(i);
						RecipeUpdate recipeUpdate = new RecipeUpdate();
						recipeUpdate.setId(obj.getString("id"));
						recipeUpdate.setPrice("$0.99");
						recipeUpdate.setName(obj.getString("name"));
						recipeUpdate.setPurchased(obj.getBoolean("bought"));
						ArrayList<Pair<String, String>> recipes = new ArrayList<Pair<String, String>>();
						JSONArray recipeJSONArray = obj.getJSONArray("files");
						for (int j = 0; j < recipeJSONArray.length(); j++) {
							JSONObject recipeObject = recipeJSONArray
									.getJSONObject(j);
							Pair<String, String> recipe = new Pair<String, String>(
									recipeObject.getString("fileName"),
									recipeObject.getString("filePath"));
							recipes.add(recipe);
						}
						recipeUpdate.setItems(recipes);
						recipeUpdates.add(recipeUpdate);
					}
				} catch (Exception e) {}

			}
			return recipeUpdates;
		}

		@Override
		protected void onPostExecute(List<RecipeUpdate> result) {
			mDialog.dismiss();
			if (result != null) {
				try {
					recipesList = result;
					listAdapter = new RecipeUpdateListAdapter(
							ActivityUpdate.this,
							R.layout.list_item_recipe_update, recipesList);
					listviewRecipes.setAdapter(listAdapter);
				} catch (Exception e) {

				}
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			mDialog = new ProgressDialog(getParent());
			mDialog.setMessage("Getting update list...");
			mDialog.setCancelable(false);
			mDialog.show();
			super.onPreExecute();
		}

	}
}
